package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjWorkBackVisitTemplateField;
import com.zb.entity.ZjWorkBackVisitTemplateFieldContent;
import com.zb.mapper.ZjWorkBackVisitTemplateFieldMapper;
import com.zb.service.ZjWorkBackVisitTemplateFieldContentService;
import com.zb.service.ZjWorkBackVisitTemplateFieldService;
import com.zb.vo.WorkFieldContentVo;
import com.zb.vo.WorkStatementTemplateFieldVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单回访模板字段表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-08
 */
@Service
public class ZjWorkBackVisitTemplateFieldServiceImpl extends ServiceImpl<ZjWorkBackVisitTemplateFieldMapper, ZjWorkBackVisitTemplateField> implements ZjWorkBackVisitTemplateFieldService {
    @Resource
    private ZjWorkBackVisitTemplateFieldMapper workBackVisitTemplateFieldMapper;
    @Resource
    private ZjWorkBackVisitTemplateFieldContentService workBackVisitTemplateFieldContentService;

    // 保存回访模板字段
    @Override
    public void save(Long custAccId, Long workBackVisitTemplateId, List<WorkStatementTemplateFieldVo> templateField) {
        if (null == templateField || templateField.isEmpty()) {
            return;
        }
        Assert.isTrue(templateField.size() <= 20, "回访自定义字段最多允许添加20个");
        Assert.isTrue(
                templateField.stream().map(WorkStatementTemplateFieldVo::getName).toList().size() == templateField.stream().map(WorkStatementTemplateFieldVo::getName).collect(Collectors.toSet()).size(),
                "回访自定义字段名称已重复"
        );

        List<ZjWorkBackVisitTemplateField> adds = new ArrayList<>();
        List<ZjWorkBackVisitTemplateField> updates = new ArrayList<>();
        ZjWorkBackVisitTemplateField field = null;
        List<ZjWorkBackVisitTemplateFieldContent> addCons = new ArrayList<>();
        List<ZjWorkBackVisitTemplateFieldContent> updateCons = new ArrayList<>();
        ZjWorkBackVisitTemplateFieldContent content = null;
        List<Long> delContentIds = new ArrayList<>();

        for (WorkStatementTemplateFieldVo vo : templateField) {
            field = new ZjWorkBackVisitTemplateField();
            BeanUtil.copyProperties(vo, field);
            field.setDisabled(vo.getStatus());
            if (null != field.getId()) {
                updates.add(field);
            } else {
                field.setId(IdWorker.getId());
                field.setCustAccId(custAccId);
                field.setWorkBackVisitTemplateId(workBackVisitTemplateId);
                adds.add(field);
            }
            if (CollectionUtils.isNotEmpty(vo.getDelContentIds())) {
                delContentIds.addAll(vo.getDelContentIds());
            }

            for (WorkFieldContentVo contentVo : vo.getContentVos()) {
                content = new ZjWorkBackVisitTemplateFieldContent();
                BeanUtil.copyProperties(contentVo, content);
                if (null != content.getId()) {
                    updateCons.add(content);
                    continue;
                }
                content.setId(IdWorker.getId());
                content.setCustAccId(custAccId);
                content.setWorkBackVisitTemplateFieldId(field.getId());
                addCons.add(content);
            }
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
        if (!addCons.isEmpty()) workBackVisitTemplateFieldContentService.saveBatch(addCons);
        if (!updateCons.isEmpty()) workBackVisitTemplateFieldContentService.updateBatchById(updateCons);
        if (!delContentIds.isEmpty()) workBackVisitTemplateFieldContentService.removeByIds(delContentIds);
    }

    // 根据回访ID获取回访字段
    @Override
    public List<WorkStatementTemplateFieldVo> getByWorkBackVisitTemplateId(Long workBackVisitTemplateId) {
        QueryWrapper<ZjWorkBackVisitTemplateField> wrapper = new QueryWrapper<>();
        wrapper.eq("work_back_visit_template_id", workBackVisitTemplateId);
        List<ZjWorkBackVisitTemplateField> templateFieldList = this.list(wrapper);
        List<Long> ids = templateFieldList.stream().map(ZjWorkBackVisitTemplateField::getId).toList();
        List<ZjWorkBackVisitTemplateFieldContent> contents = workBackVisitTemplateFieldContentService.getByWorkBackVisitTemplateFieldIds(ids);

        return templateFieldList.stream().map(tem -> {
            WorkStatementTemplateFieldVo vo = new WorkStatementTemplateFieldVo();
            BeanUtil.copyProperties(tem, vo);
            vo.setStatus(tem.getDisabled());
            vo.setContentVos(contents.stream().filter(f -> Objects.equals(f.getWorkBackVisitTemplateFieldId(), vo.getId())).map(con -> {
                WorkFieldContentVo cv = new WorkFieldContentVo();
                BeanUtil.copyProperties(con, cv);
                return cv;
            }).toList());
            return vo;
        }).toList();
    }

    // 根据回访模板ID删除
    @Override
    public void deleteBatchByWorkBackVisitTemplateIds(List<Long> workBackVisitTemplateIds) {
        if (CollectionUtils.isEmpty(workBackVisitTemplateIds)) {
            return;
        }
        QueryWrapper<ZjWorkBackVisitTemplateField> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        wrapper.in("work_back_visit_template_id", workBackVisitTemplateIds);
        List<Long> ids = this.list(wrapper).stream().map(ZjWorkBackVisitTemplateField::getId).toList();
        workBackVisitTemplateFieldContentService.deleteBatchByWorkBackVisitTemplateFieldIds(ids);
        this.removeByIds(ids);
    }

    // 根据回访模板ID查询
    @Override
    public List<ZjWorkBackVisitTemplateField> getByWorkBackVisitTemplateIds(List<Long> workBackVisitTemplateIds) {
        if (CollectionUtils.isEmpty(workBackVisitTemplateIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkBackVisitTemplateField> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        wrapper.in("work_back_visit_template_id", workBackVisitTemplateIds);
        return this.list(wrapper);
    }

    // 根据回访字段ID查询关联信息
    @Override
    public List<ZjWorkBackVisitTemplateField> getRelationByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        // todo 查询关联信息
        return new ArrayList<>();
    }

    // 根据回访模板自定义字段ID获取字段详情
    @Override
    public WorkStatementTemplateFieldVo getFieldDetail(Long id) {
        ZjWorkBackVisitTemplateField templateField = this.getById(id);
        Assert.isTrue(null != templateField, "回访模板自定义字段参数ID[" + id + "]的数据不存在！");

        WorkStatementTemplateFieldVo vo = new WorkStatementTemplateFieldVo();
        BeanUtil.copyProperties(templateField, vo);
        vo.setStatus(templateField.getDisabled());
        vo.setContentVos(workBackVisitTemplateFieldContentService.getByWorkBackVisitTemplateFieldId(id).stream().map(con -> {
            WorkFieldContentVo convo = new WorkFieldContentVo();
            BeanUtil.copyProperties(con, convo);
            return convo;
        }).toList());
        return vo;
    }

    // 批量启用或禁用回访模板自定义字段
    @Override
    public void updateDisableBatchById(List<Long> ids, boolean status) {
        workBackVisitTemplateFieldMapper.updateDisableBatchById(ids, status);
    }

    // 批量删除回访模板自定义字段
    @Override
    public void deleteBatchById(List<Long> ids) {
        List<ZjWorkBackVisitTemplateField> relation = getRelationByIds(ids);
        Assert.isTrue(CollectionUtils.isEmpty(relation), "回访自定义字段[" + relation.stream().map(ZjWorkBackVisitTemplateField::getName).collect(Collectors.joining("、")) + "]已被使用中，不可删除！");
        workBackVisitTemplateFieldContentService.removeByWorkBackVisitTemplateFieldIds(ids);
        this.removeByIds(ids);
    }
}
